const router = require('koa-router')()
const Location = require('../dbs/models/location')
const LocationHistory = require('../dbs/models/locationHistory')

router.prefix('/changeCity')

router.get('/city', async function (ctx) {
  let code, msg, result
  try {
    result = await Location.findOne()
    code = 0
    msg = '查询成功'
  } catch (error) {
    code = -1,
    msg = error
  }
  ctx.body = {
    result,
    code,
    msg
  }
})

/** 写最近访问城市记录 最多十条 */
router.post('/addVisitCity', async (ctx) => {
  let result, code, msg, search, city
  try {
    result = await LocationHistory.findOne()
    search = result.searchCity
    city = ctx.request.body.city
    if (search && search.length > 10) {
      if (!search.includes(city)) 
        await LocationHistory.update({searchCity: [...search.slice(0, 9), city]})
    }
    else {
      if (!search.includes(city)) 
        await LocationHistory.update({searchCity: [...search, city]})
    }
    code = 0
    msg = '成功'
  } catch (error) {
    code = -1
    msg = error
    result = []
  }
  ctx.body = {
    code,
    msg,
    result
  }
})

/** 查询最近访问城市 */
router.get('/getCityHistory', async (ctx) => {
  let code, result, msg
  try {
    result = await LocationHistory.findOne()
    code = 0
    msg = '成功'
  } catch (error) {
    code = -1
    msg = '失败'
  }
  ctx.body = {
    result,
    code, 
    msg
  }
})

module.exports = router